# 14.使用模板
import uvicorn
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import HTMLResponse
from starlette.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

# 测试数据
books = [
    {"id": 1, "title": "看漫画学Python", "author": "关东升", "price": 29.99},
    {"id": 2, "title": "杀死一只知更鸟", "author": "Harper Lee", "price": 19.99},
    {"id": 3, "title": "Python从小白到大牛", "author": "关东升", "price": 49.99},
    {"id": 4, "title": "漫画Java", "author": "关东升", "price": 39.99},
]


@app.get("/books/", response_class=HTMLResponse)
def get_book_list(request: Request):
    return templates.TemplateResponse(
        name="books.html", context={"request": request, "book_list": books}
    )


@app.get("/book/{price}", response_class=HTMLResponse)
def get_book_list(price: float, request: Request):
    # 长字符串
    info = """
        书名：《Python从小白到大牛》
    作者：关东升
    """
    return templates.TemplateResponse(
        name="book_info.html", context={"request": request, "price": price, "info": info}
    )


if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
